package lee.study.Data_Struct.Hash;

import java.util.Objects;

class Person {
    public int id;

    public Person(int id) {
        this.id = id;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Person person = (Person) o;
        return id == person.id;
    }

    @Override
    public int hashCode() {
        return Objects.hash(id);
    }
}

public class HashBuck2<K, V> {
    static class Node<K, V> {
        public K key;
        public V val;
        public Node<K, V> next;

        public Node(K key, V val) {
            this.key = key;
            this.val = val;
        }

    }
        public Node<K, V>[] array = (Node<K, V>[]) new Node[10];
        public int usedSize;
        public void put(K key, V val) {
            int hash = key.hashCode();
            int index = hash % array.length;
            //不能直接用hashCode得到的值对数组长度取余，
            // hashCode得到的值是引用，先转换为int再取余
            for (Node<K, V> cur = array[index]; cur != null; cur = cur.next) {
                if (cur.key.equals(key)) {
                    //对象的比较必须使用equals方法且equals方法必须重写过！！！
                    cur.val = val;
                    return;
                }
            }
            Node<K, V> node = new Node<>(key, val);
            node.next = array[index];
            array[index] = node;
            this.usedSize++;
        }


        public V get(K key) {
            //1、找位置
            int hash = key.hashCode();
            int index = hash % array.length;
            //2、遍历单链表 找到返回值val
            Node<K, V> cur = array[index];
            while (cur != null) {
                if (cur.key.equals(key)) {
                    return cur.val;
                } else {
                    cur = cur.next;
                }
            }
            return null;
        }

    public static void main(String[] args) {
        Person person1 = new Person(12);
        Person person2 = new Person(12);
        HashBuck2<Person, String> hashBuck2 = new HashBuck2<>();
        hashBuck2.put(person1, "shabi");
        System.out.println(hashBuck2.get(person2));
    }

}

